package net;

import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;

/**
 * @author liweimin
 * @date 2021/4/6 18:22
 * @description network test
 * @since
 */
public class WebTest {
    @Test
    public void test1() throws UnknownHostException {
        //有缓存
        InetAddress localHost = InetAddress.getLocalHost();
        System.out.println(localHost);
        InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
        System.out.println(loopbackAddress);

        InetAddress address = InetAddress.getByName("www.baidu.com");
        System.out.println(address);
        InetAddress byAddress = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
        System.out.println(byAddress);

        InetAddress atGuiGu = InetAddress.getByName("www.atguigu.com");
        System.out.println(atGuiGu);
    }

    /**
     * tcp socket测试
     *
     * @throws IOException
     */
    @Test
    public void test2() throws IOException {
        //先建立服务端Socket
        ServerSocket serverSocket = new ServerSocket(9999);

        //接受客户端请求，接受连接
        serverSocket.accept();

        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);

        //获取输入流--->接受消息
        InputStream inputStream = socket.getInputStream();

        //获取输出流--->发送消息
        OutputStream outputStream = socket.getOutputStream();

        //获取该套接字连接的远程ip地址
        InetAddress inetAddress = socket.getInetAddress();

        //获取该套接字的本地ip地址
        InetAddress localAddress = socket.getLocalAddress();

        int localPort = socket.getLocalPort();
        System.out.println(localPort);

        outputStream.write("hello world".getBytes());
        socket.close();
    }

    @Test
    public void test3() throws IOException {
        DatagramSocket datagramSocket = new DatagramSocket();
        byte[] bytes = "hello world".getBytes();
        DatagramPacket datagramPacket = new DatagramPacket(bytes, 0, bytes.length, InetAddress.getLocalHost(), 10000);
        datagramSocket.send(datagramPacket);
        datagramSocket.close();
    }

    @Test
    public void test4() throws MalformedURLException {
        URL url = new URL("http://www.atguigu.com/");
        URL search = new URL(url, "search?x=13&y=12");
        System.out.println(search);
        System.out.println(search.getFile());
        System.out.println(search.getQuery());
    }

    @Test
    public void test5() throws IOException {
        URL url = new URL("http://www.atguigu.com/index.shtml");

        //能从网络上读取数据，向CGI[Common Gateway Interface]发送数据
        URLConnection urlConnection = url.openConnection();
    }
}
